﻿@page "/publish/course/{CourseId:int}"
@using AntDesign.TableModels
@using lcwb.Shared.Service
@using System.ComponentModel.DataAnnotations
@inject CourseService CourseService
@inject MessageService Message
@inject ModalService ModalService
@inject NavigationManager Navigation

<AntDesign.PageHeader 
Title="章节管理" 
OnBack="@(() => Navigation.NavigateTo($"/publish/course"))">
</AntDesign.PageHeader>

<Table TItem="Chapter" 
DataSource="_dataSource"
Total="_total"
PageSize="10"
@ref="_table"
OnChange="OnTableChange"
Bordered
Size="TableSize.Middle">

    <TitleTemplate>
        <Flex Justify="FlexJustify.SpaceBetween">
            <Space>
                <Button Type="ButtonType.Primary" OnClick="ShowCreateModal">
                    <Icon Type="plus" /> 新增章节
                </Button>
                <Button Danger
                Disabled="!_selectedChapters.Any()"
                OnClick="DeleteSelected">
                    批量删除
                </Button>
            </Space>
        </Flex>
    </TitleTemplate>
    <ColumnDefinitions Context="chapter">
        <Selection />
        <PropertyColumn Title="章节名称"
        Property="@(c => c.Title)"
        Sortable 
        Filterable>
            <Template>
                <b>@chapter.Title.ToUpper()</b>
            </Template>
        </PropertyColumn>
        <PropertyColumn Title="Order" Property="@(c => c.Order)" Sortable />
        <ActionColumn Title="操作" Width="150px">
            <Space>
                <Button Type="ButtonType.Link"
                OnClick="@(() =>Nav2ResourceAdmin(chapter.CourseId,chapter.Id))">
                    管理资源
                </Button>
                <Button Type="ButtonType.Link" 
                OnClick="@(() => ShowEditModal(chapter))">
                    编辑
                </Button>
                <Popconfirm Title="确认删除？" 
                OnConfirm="@(() => DeleteChapter(chapter))">
                    <Button Type="ButtonType.Link" Danger>
                        删除
                    </Button>
                </Popconfirm>
            </Space>
        </ActionColumn>
    </ColumnDefinitions>
</Table>

<Modal @bind-Visible="modalVisible" 
Title="@(isEditMode ? "编辑章节" : "新增章节")"
OnOk="SubmitForm">
    <Form Model="@currentChapter">
        <FormItem Label="章节名称" 
        Rules="@(new[] { new FormValidationRule { Required = true } })">
            <Input @bind-Value="currentChapter.Title" />
        </FormItem>
        <FormItem Label="排序序号" 
        Rules="@(new[] { new FormValidationRule { Type = FormFieldType.Number } })">
            <Input @bind-Value="currentChapter.Order" />
        </FormItem>
    </Form>
</Modal>

@code {
    [Parameter] public int CourseId { get; set; }
    protected override void OnParametersSet() => CourseId = CourseId;
    private ITable _table;
    private List<Chapter> _allChapters = new();
    private List<Chapter> _dataSource = new();
    private IEnumerable<Chapter> _selectedChapters = new List<Chapter>();
    private int _total;
    private Chapter currentChapter = new();
    private bool modalVisible;
    private bool isEditMode;

    protected override async Task OnInitializedAsync()
    {
        await LoadData();
    }

    private async Task LoadData()
    {
        _allChapters = await CourseService.GetChapters(CourseId);
        _allChapters.Add(
            new Chapter()
            {
                Id = 0,
                CourseId = CourseId,
                Title = "Info",
                Order = 0
            }
        );
        _total = _allChapters.Count;

        _table.ReloadData();
    }

    private void OnTableChange(QueryModel<Chapter> query)
    {
        var queryable = _allChapters.AsQueryable();
        _dataSource = queryable.ExecuteTableQuery(query)
                              .CurrentPagedRecords(query)
                              .ToList();
    }

    private void ShowCreateModal()
    {
        currentChapter = new Chapter { CourseId = CourseId };
        isEditMode = false;
        modalVisible = true;
    }

    private void ShowEditModal(Chapter chapter)
    {
        currentChapter = chapter;
        isEditMode = true;
        modalVisible = true;
    }

    private void Nav2ResourceAdmin(int CourseId, int ChapterId)
    {
        Navigation.NavigateTo($"/publish/course/{CourseId}/chapters/{ChapterId}/resources");
    }

    private async Task SubmitForm()
    {
        if (isEditMode)
        {
            //await ChapterService.UpdateChapterAsync(currentChapter);
        }
        else
        {
            //await ChapterService.CreateChapterAsync(currentChapter);
        }
        
        modalVisible = false;
        await LoadData();
        await Message.Success(isEditMode ? "更新成功" : "新增成功");
    }

    private async Task DeleteChapter(Chapter chapter)
    {
        //await ChapterService.DeleteChapterAsync(chapter.Id);
        await LoadData();
        await Message.Success("删除成功");
    }

    private async Task DeleteSelected()
    {
        //await ChapterService.DeleteChaptersAsync(_selectedChapters.Select(c => c.Id));
        await LoadData();
    }
}